package com.longqinuo.mycarservice.fragments;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.longqinuo.mycarservice.BuildConfig;
import com.longqinuo.mycarservice.R;
import com.longqinuo.mycarservice.utils.PathUtils;
import com.longqinuo.mycarservice.utils.SPUtils;
import com.longqinuo.mycarservice.view.CircleNetworkImage;
import com.longqinuo.mycarservice.view.LruImageCache;


import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link UserDataFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class UserDataFragment extends Fragment implements View.OnClickListener {
    private RequestQueue queue;

    private ImageLoader imageLoader;
    private ViewPager mViewPager;

    private FragmentManager manager;
    private FragmentTransaction mTransaction;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private String pics[] = {"相机","相册","取消"};


    private OnFragmentInteractionListener mListener;
    private ImageView mBack;
    private TextView mTitle;
    private ImageView mOption;
    private CircleNetworkImage cni_header_change;
    private String headerUrl;
    private TextView tv_name_change;
    private TextView tv_phone_change;
    private Button btn_exit_login;
    private String mName;
    private String mPhone;

    public final static int ALBUM_REQUEST_CODE = 1;   //相册请求
    public final static int CAMERA_REQUEST_CODE = 3;   //相机请求
    // 拍照路径


    private String cameraPath;
    public UserDataFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserDataFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static UserDataFragment newInstance(String param1, String param2) {
        UserDataFragment fragment = new UserDataFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        manager = getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(getActivity());
        LruImageCache lruImageCache = LruImageCache.instance();
        imageLoader = new ImageLoader(queue,lruImageCache);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_data, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {

        mBack = (ImageView) view.findViewById(R.id.iv_top_back);
        mBack.setOnClickListener(this);
        mTitle = (TextView) view.findViewById(R.id.tv_top_title);
        mTitle.setText("个人资料");
        mOption = (ImageView) view.findViewById(R.id.iv_top_option);
        mOption.setVisibility(View.INVISIBLE);
        cni_header_change = (CircleNetworkImage) view.findViewById(R.id.cni_header_change);
        cni_header_change.setOnClickListener(this);
        tv_name_change = (TextView) view.findViewById(R.id.tv_name_change);
        tv_name_change.setOnClickListener(this);
        tv_phone_change = (TextView) view.findViewById(R.id.tv_phone_change);
        tv_phone_change.setOnClickListener(this);
        btn_exit_login = (Button) view.findViewById(R.id.btn_exit_login);
        btn_exit_login.setOnClickListener(this);
        headerUrl = PathUtils.LOAD_HEADER+SPUtils.getSp(getActivity(),"headerPath","");
        cni_header_change.setImageUrl(headerUrl,imageLoader);
        mName = (String) SPUtils.getSp(getActivity(),"userName","点击修改");
        tv_name_change.setText(mName);
        mPhone = (String) SPUtils.getSp(getActivity(),"userPhone","点击修改");
        tv_phone_change.setText(mPhone);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewPager = (ViewPager) getActivity().findViewById(R.id.id_main_view_pager);
    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_top_back:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
            case R.id.cni_header_change:
                Toast.makeText(getActivity(), "修改头像", Toast.LENGTH_SHORT).show();
                doChangeHeader();
                break;
            case R.id.tv_phone_change:
                Toast.makeText(getActivity(), "修改手机号", Toast.LENGTH_SHORT).show();
                break;
            case R.id.tv_name_change:
                Toast.makeText(getActivity(), "修改用户名", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_exit_login:
                SPUtils.removeSP(getActivity(),"isLogin");
                SPUtils.removeSP(getActivity(), "userPhone");
                SPUtils.removeSP(getActivity(), "userPwd");
                SPUtils.removeSP(getActivity(), "userId");
                SPUtils.removeSP(getActivity(), "userName");
                SPUtils.removeSP(getActivity(),"headerPath");
                PathUtils.havedLogin = false;
                mTransaction = manager.beginTransaction();
                mViewPager.setCurrentItem(0,true);
                UserDataFragment userDataFragment = (UserDataFragment) manager.findFragmentByTag("UserData");
                mTransaction.remove(userDataFragment);
                mTransaction.commit();
                break;
        }
    }

    private void doChangeHeader() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle(R.string.change_header_image);

        builder.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, pics), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        doCamera();  //跳转拍照
                        break;
                    case 1:
                        doAlbum();   //跳转相册
                        break;
                    case 2:     //关闭对话框
                        builder.create().dismiss();
                        break;
                }
            }
        });

        builder.create().show();
    }
    private void doAlbum() {   //获取相册中的图片
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, ALBUM_REQUEST_CODE);
    }

    private void doCamera() {
        // 指定相机拍摄照片保存地址
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            cameraPath = PathUtils.SAVED_IMAGE_DIR_PATH +
                    System.currentTimeMillis() + ".png";
            Intent intent = new Intent();
            // 指定开启系统相机的Action
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            String out_file_path = PathUtils.SAVED_IMAGE_DIR_PATH;
            File dir = new File(out_file_path);    if (!dir.exists()) {
                dir.mkdirs();
            }
            // 把文件地址转换成Uri格式
            Uri uri = Uri.fromFile(new File(cameraPath));
            // 设置系统相机拍摄照片完成后图片文件的存放地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, CAMERA_REQUEST_CODE);
        } else {
            Toast.makeText(getActivity(), "请确认已经插入SD卡",
                    Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public void onActivityResult(int requestCode,
                                 int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (BuildConfig.DEBUG) Log.d("UserDataFragment", "双向跳转返回");
        if (resultCode == Activity.RESULT_OK) {    //相机返回

            if (requestCode == ALBUM_REQUEST_CODE) {    //相册返回
                try {

                    Uri uri = data.getData();
                    final String absolutePath=
                            getAbsolutePath(getActivity(), uri);
                    if (BuildConfig.DEBUG) Log.d(">>>>>", absolutePath);
                    cameraPath = absolutePath;
                } catch (Exception e) {
                    e.printStackTrace();

                }
            }
            doUpdate(cameraPath);
        }


    }

    public void doUpdate(String path) {
        int id = (int) SPUtils.getSp(getActivity(),"userId",0);
        String url = PathUtils.UPDATE_HEADER_URL;
        if (BuildConfig.DEBUG) Log.d(">>>>>>", url);
        RequestParams params = new RequestParams(url);
        // 加到url里的参数, http://xxxx/s?wd=xUtils
        params.addParameter("id",id);
        // 添加到请求body体的参数, 只有POST, PUT, PATCH, DELETE请求支持.
        params.addBodyParameter(
                "headPhoto",
                new File(path),
                "image/*"); // 如果文件没有扩展名, 最好设置contentType参数.
        x.http().request(HttpMethod.POST,params,new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    int code = jsonObject.getInt("code");
                    switch (code) {
                        case 0:
                            saveHeaderUrl(jsonObject);
                            break;
                        default:
                            Toast.makeText(getActivity(), "上传图片过大", Toast.LENGTH_SHORT).show();
                            break;

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), "服务器繁忙或异常", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "上传被取消", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                if (BuildConfig.DEBUG) Log.d(">>>>>>>>", "上传结束");
            }
        });
    }
    public void saveHeaderUrl(JSONObject jsonObject) throws JSONException {
        String data = jsonObject.getString("data");
        Toast.makeText(getActivity(), "上传成功", Toast.LENGTH_SHORT).show();
        SPUtils.setSP(getActivity(),"headerPath",data);
        headerUrl = PathUtils.LOAD_HEADER+SPUtils.getSp(getActivity(),"headerPath","");
        cni_header_change.setImageUrl(headerUrl,imageLoader);
    }

    public String getAbsolutePath(final Context context,
                                  final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(
                            MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }     return data;
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
